<template>
  <div class="cartWrapper">
    <div class="cart-box">
      <address :address-data="addressData" @click="selectAddress"></address>
      <div class="h1"></div>
      <group>
        <popup-picker :value.sync="timeValue" title="送达时间" :data="sendtime"></popup-picker>
      </group>
      <!--<div class="cart-item">-->
      <!--<img src="http://static.52letsgo.cn/zz/wechatimg/ic_time.png">-->
      <!--&lt;!&ndash;<p>送达时间:08:00~08:15</p>&ndash;&gt;-->
      <!--&lt;!&ndash;<img class="right-arrow" src="http://static.52letsgo.cn/zz/wechatimg/ic_right_arrow.png">&ndash;&gt;-->
      <!--</div>-->
      <!--<div class="h1"></div>-->
      <!--<div class="cart-item coupon-box" @click="selectCoupon">
        <p>优惠券</p>
        <img class="right-arrow" src="http://static.52letsgo.cn/zz/wechatimg/ic_right_arrow.png">
        <p class="coupon-info">{{couponName}}</p>
      </div>-->
      <group @click="selectCoupon">
        <cell title="优惠券" :value="couponName" is-link></cell>
      </group>
      <group>
        <x-input title="订单备注" :value.sync="mark" placeholder="订单备注(选填)" type="text"></x-input>
      </group>
      <div class="h1"></div>
      <!--<div class="text-item"><p>早范早餐</p></div>-->
      <!--<div class="line1"></div>-->
      <div class="product-box">
        <product-item @refresh="init" :active="activeDay" :product="item"
                      v-for="(index,item) in products"></product-item>
      </div>
      <div class="h1"></div>
      <!--<div class="remark-box">
        <input v-model="mark" placeholder="订单备注(选填)" type="text">
      </div>-->
      <div class="cart-total-box-height"></div>
      <div class="cart-total-box">
        <div class="cart-num-container">
          <img src="http://static.52letsgo.cn/zz/wechatimg/ic_user_cart.png" alt="">
          <div class="product-num"><p>{{cartInfo.num}}</p></div>
        </div>
        <!--<div class="line"></div>-->
        <div class="total-price">合计:<span>{{cartInfo.price | currency ' '}}</span></div>
        <div @click="toPay" class="pay-btn">结算</div>
        <!--<p>￥</p>
        <p>{{cartInfo.price}}</p>
        <p @click="toPay" class="cart-settlement">结算</p>-->
      </div>
    </div>
    <confirm-pay :show="showConfirm" @on-cancel="onCancel" @on-confirm="onConfirm">

    </confirm-pay>
  </div>
</template>
<script>
  import {couponClick, selectedCoupon, addressClick} from './../../vuex/getters.js'
  import {set_couponClick, set_selectedCoupon, update_address_click} from './../../vuex/actions.js'
  import Address from './address.vue'
  import ProductItem from './cartItem.vue'
  import PopupPicker from './../../components/popup-picker/index.vue'
  import {Group, Cell, XInput,confirm} from './../../components'
  import confirmPay from './confirmPay.vue'
  var MyRequest = require('./../../commons/js/MyRequest');
  var utils = require('./../../commons/js/utils');
  var CartUtils = require('./../../commons/js/Cart');
  var Global = require('./../../commons/js/Global');
  var MyRequire = require('./../../commons/js/MyRequest');
  var LocalStorageUtil = require('./../../commons/js/LocalStorageUtil.js')
  export default{
    data(){
      return {
        products: [],
        cartInfo: {},
        mark: "",
        activeDay: [],
        addressData: new Object(),
        couponName: '选择优惠券',
        sendtime: [['08:00～08:15', '08:15～08:30', '08:30～08:45',
          '08:45～09:00', '09:00～09:15', '09:15～09:30']],
        timeValue: ['08:00～08:15'],
        showConfirm:false
      }
    },
    components: {
      Address,
      ProductItem,
      PopupPicker,
      Group,
      Cell,
      XInput,
      confirm,
      confirmPay
    },
    vuex: {
      getters: {
        couponClick,
        selectedCoupon,
        addressClick
      },
      actions: {
        set_couponClick,
        set_selectedCoupon,
        update_address_click
      }
    },
    created: function () {
      var localAddress = LocalStorageUtil.getItem("Address")
      if (this.selectedCoupon) {
        this.couponName = this.selectedCoupon.name
      } else {
        this.couponName = '选择优惠券'
      }
      if (localAddress) {
        this.addressData = localAddress
      }
    },
    methods: {
      init(){
        var carts = CartUtils.getCartStorage();
        this.products = carts;
        this.cartInfo = {
          num: CartUtils.countCartNum(),
          price: CartUtils.getTotalPrice()
        }
        if (this.selectedCoupon){
            if (this.selectedCoupon.conditions > CartUtils.getTotalPrice()){
              this.couponName = '选择优惠券';
              this.set_selectedCoupon('');
            }
        }
      },
      toPay(){
        if (!this.products || this.products.length<=0){
          Global.showToast("购物车为空，请先添加商品",this);
          return;
        }
        this.showConfirm = true;
      },
      selectCoupon () {
        if (!LocalStorageUtil.getItem("User")) {
          this.$router.go({path: '/login'})
        } else {
          this.set_couponClick(true)
          this.$router.go({path: '/couponList'})
        }
      },
      selectAddress () {
        if (!LocalStorageUtil.getItem("User")) {
          this.$router.go({path: '/login'})
        } else {
          this.update_address_click(true)
          this.$router.go({path: '/addressList'})
        }
      },
      getActiveDay(){
        var data = {
          action: "weekday"
        };
        MyRequest.MyGetWithToast("ActiveDay", this, function (result, that) {
          console.log(result);
          Global.closeLoading()
          var data = result.data;
          Global.closeLoading();
          var dateList = new Array();
          for (var i = 0; i < data.length; i++) {
            if (data[i].state != 1) {
              var weekday = utils.solveDate(data[i].wday);
              dateList.push(data[i].wdate + "-" + weekday);
            }
          }

          var d = new Array();
          d.push(dateList);
          that.activeDay = d;

        }, data);
      },
      orderSubmit() {
        var localAddress = LocalStorageUtil.getItem("Address");
        var shopData = CartUtils.getOrderList();
        var user = LocalStorageUtil.getItem("User");
        var orderInfo = {
          "address": localAddress.id,
          "mark": this.mark,
          "mobile": user.mobile,
          "time": this.timeValue[0],
          "userId": user.id,
          "shopData": shopData
        }
        if (this.selectedCoupon) {
          orderInfo.couponId = this.selectedCoupon.couponId;
          orderInfo.couponUserId = this.selectedCoupon.id;
          this.set_selectedCoupon('');
        }
        var newOrderInfo = JSON.stringify(orderInfo);
        newOrderInfo.replace('\"', "'");
        var data = {
          action: "packages",
          platform: Global.getPlatform(),
          userId: user.id,
          cityId: localAddress.cityId,
          areaId: localAddress.areaId,
          orderInfo: newOrderInfo
        };
        MyRequire.MyPostWithToast("OrderSubmit", this, function (result, that) {
          that.set_selectedCoupon('');
          CartUtils.clearCartStorage();
          console.log(result);
          if (result.success) {
            var data = result.data;
            that.$router.go({
              name: 'pay', query: {
                freePrice: data.freePrice,
                orderId: data.orderId,
                orderNo: data.orderNo,
                orderTime: data.orderTime,
                totalPrice: data.totalPrice
              }
            });
            Global.closeLoading();
          }else{
            Global.showToast(result.msg,that);
          }
        }, data);
      },
      onConfirm(){
        var localAddress = LocalStorageUtil.getItem("Address");
        if (!localAddress) {
          Global.showToast("请选择地址", this);
          return;
        }
        this.orderSubmit();
      },
      onCancel(){
        this.showConfirm = false;
      }
    },
    ready: function () {
      this.init();
      this.getActiveDay();
    }
  }
</script>
<style lang="less">
  @import './cart.less';

</style>
